package com.test.auth_db_auto.support.oauth2;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.test.auth_db_auto.config.ContextHolderUtils;
import com.test.auth_db_auto.exception.AuthFailureException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 定义异常MyOAuth2Exception的序列化
 * @ Author: .Mr
 * @ ClassName BootOAuth2ExceptionJacksonSerializer
 * @ Description TODO
 * @ date 2021/12/22 11:02
 * @ Version 1.0
 */
public class BootOAuth2ExceptionJacksonSerializer extends StdSerializer<BootOAuth2Exception> {

    protected BootOAuth2ExceptionJacksonSerializer(){super(BootOAuth2Exception.class);}
    @Override
    public void serialize(BootOAuth2Exception e, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {

        HttpServletRequest request = ContextHolderUtils.getRequest();
        json.writeStartObject();
        json.writeObjectField("code", e.getHttpErrorCode());
        json.writeStringField("path",request.getServletPath());
        json.writeStringField("timestamp",String.valueOf(System.currentTimeMillis()));
        String errorMessage=e.getOAuth2ErrorCode();
        if(errorMessage!=null){
            errorMessage= HtmlUtils.htmlEscape(errorMessage);
        }
        String message=e.getMessage();
        if(message.contains("Invalid authorization code:")){
            String [] info=message.split(":");
            json.writeStringField("msg","授权码无效:"+info[1]);
        }else if(message.contains("Invalid refresh token:")){
            String [] info=message.split(":");
            json.writeStringField("msg","refresh_token无效:"+info[1]);
        }else if(message.contains("Redirect URI mismatch")){
            json.writeStringField("msg","验证失败，Redirect URI mismatch");
        } else{
            json.writeStringField("msg",message);
        }
        if(e.getAdditionalInformation()!=null){
            for (Map.Entry<String, String> entry : e.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                json.writeStringField(key, add);
            }
        }
        json.writeEndObject();
    }
}
